#include "beep_fun.h"
#include <Arduino.h>
#include <nvs_flash.h>
#include "common_util.h"

// 开机后，蜂鸣器开关状态
uint8_t beepDef = 0;
char* beepDef_key = "b_d_key";

// 蜂鸣器闪烁繁忙标志位
uint8_t beep_f = 0, beep_fc = 0;
TaskHandle_t taskBeepfHandle = NULL;

void beepInit() {
  nvs_get_u8(my_nvs_handle_t, beepGio_key, &beepGio);
  nvs_get_u8(my_nvs_handle_t, beepDef_key, &beepDef);

  Serial.print("Beep pin:");
  Serial.print(beepGio);
  Serial.println("   BEEP_P07   BEEP_P08");
  Serial.print("Beep def:");
  Serial.print(beepDef);
  Serial.println("   BEEP_D0   BEEP_D1");

  // 初始化蜂鸣器
  pinMode(beepGio, OUTPUT);
  if (beepDef) {
    // 响起来
    digitalWrite(beepGio, HIGH);
  } else {
    digitalWrite(beepGio, LOW);
  }

  xTaskCreate(taskBeepf, "taskBeepf", 512, NULL, 1, &taskBeepfHandle);
}

void taskBeepf(void* ptParam) {
  while (true) {
    if (beep_f) {
      beep_f = 0;
      for (uint8_t i = 0; i < beep_fc; i++) {
        digitalWrite(beepGio, HIGH);
        delay(500);
        digitalWrite(beepGio, LOW);
        delay(500);
      }
    } else {
      vTaskSuspend(NULL);
    }
  }
}

uint8_t requestBeep(String request, int len) {
  if (!(request.startsWith("BEEP_") || request.startsWith("beep_"))) {
    return 0;
  }
  if (len < 6) {
    return 1;
  }
  char c5 = request.charAt(5);
  if ((c5 == 'P' || c5 == 'p') && len >= 8) {
    Serial.print("Set beep pin:");
    uint8_t pin = (request.charAt(6) - '0') * 10 + (request.charAt(7) - '0');
    saveVlaueU8(beepGio_key, pin);
    Serial.println(pin);
    return 1;
  }

  if ((c5 == 'D' || c5 == 'd') && beepGio < 99 && len >= 7) {
    Serial.print("Set beep def:");
    if (request.charAt(6) == '1') {
      saveVlaueU8(beepDef_key, 1);
      Serial.println(1);
    } else {
      saveVlaueU8(beepDef_key, 0);
      Serial.println(0);
    }
    return 1;
  }

  if ((c5 == 'B' || c5 == 'b') && beepGio < 99 && len >= 7) {
    if (request.charAt(6) == '1') {
      digitalWrite(beepGio, HIGH);
    } else {
      digitalWrite(beepGio, LOW);
    }
    return 1;
  }

  if (c5 == 'F' || c5 == 'f') {
    beep_fc = 3;
    beep_f = 1;
    vTaskResume(taskBeepfHandle);
    return 1;
  }

  if ((c5 == 'N' || c5 == 'n') && len >= 7) {
    beep_fc = request.charAt(6) - '0';
    if (beep_fc > 10) {
      beep_fc = 1;
    }
    beep_f = 1;
    vTaskResume(taskBeepfHandle);
    return 1;
  }
  return 1;
}
